from ..base_downloader import *
from ..base_downloader_firefox import BaseDownloaderFirefox
from selenium.webdriver.common.action_chains import ActionChains


class Task44(BaseDownloaderFirefox):
    def login(self):
        username_field = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.NAME, "username"))
        )
        password_field = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.NAME, "password"))
        )
        username_field.send_keys(self.username)
        password_field.send_keys(self.password)

        captcha_input = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.NAME, "code"))
        )
        captcha_solution = solve_captcha_image(self.driver, (By.CLASS_NAME, "img-container"))
        if captcha_solution:
            captcha_input.clear()
            captcha_input.send_keys(captcha_solution)


        self.driver.find_element(By.XPATH, "//*[text()='立即登录 ']").click()

        self.random_sleep(0.5)
        self.accept_alert_dialog()
        self.random_sleep(1.5)

    def retrieve_data(self):
        self.click_query_button()
        self.random_sleep(5)       
        self.set_start_and_end_dates()
        self.random_sleep(5)   
        self.click_retrieve_button()
        self.random_sleep(5)   

    def click_query_button(self):
        try:
            confirm_button = WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.XPATH, '//button[@class="el-button el-button--primary el-button--small" and span[text()="确 定"]]'))
            )
            
            confirm_button.click()
            self.random_sleep(1)
            print("confirmed")

        except:
            print("Didn't find the button, proceed")


        try:
            supplier_zone = WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.XPATH, '//div[@class="el-submenu__title" and span[text()="供应商专区"]]'))
            )

            supplier_zone.click()
            self.random_sleep(1)
            query_button = WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable((By.XPATH, '//li[@class="el-menu-item" and span[text()="数据流向(新)"]]'))
            )
            query_button.click()
            self.random_sleep(1)

        except Exception as e:
            logger.exception(f"An error occurred while clicking the query button: {e}")

    def set_start_and_end_dates(self):

        # date_picker = WebDriverWait(self.driver, 10).until(
        #     EC.presence_of_element_located((By.CLASS_NAME, 'el-date-editor--daterange'))
        # )
        # date_picker.click()
        # time.sleep(1)

        # start_date_input = WebDriverWait(self.driver, 10).until(
        #     EC.visibility_of_element_located((By.XPATH, './/input[@placeholder="开始日期"]'))
        #     )
        # start_date_input.clear()
        # time.sleep(1)   
        # start_date_input.send_keys(self.start_date)

        # end_date_input = WebDriverWait(self.driver, 10).until(
        #     EC.visibility_of_element_located((By.XPATH, './/input[@placeholder="结束日期"]'))
        #     )
        # actions = ActionChains(self.driver)
        # actions.move_to_element(end_date_input).click().send_keys(self.end_date).perform()

        delete_time_button = WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable((By.CLASS_NAME, 'el-input__icon.el-range__close-icon'))
        )
        delete_time_button.click()

        self.capture_screenshot()

    def click_retrieve_button(self):
        try:
            retrieve_button = WebDriverWait(self.driver, 10).until(
                                EC.element_to_be_clickable((By.XPATH, '//button[@class="el-button el-button--primary el-button--small" and span[text()="搜索"]]'))
                                )
            retrieve_button.click()
            self.random_sleep(2)
            retrieve_button.click()
            self.random_sleep(20)
        except Exception as e:
            logger.exception(f"An error occurred while clicking the retrieve button: {e}")

    def export_excel(self):
        self.capture_screenshot()
        export_button = WebDriverWait(self.driver, 10).until(
                            EC.element_to_be_clickable((By.XPATH, '//button[@class="el-button el-button--primary el-button--small" and span[text()="导出明细"]]'))
                        )
        export_button.click()
        self.random_sleep(1)

        download_side = WebDriverWait(self.driver, 10).until(
                            EC.presence_of_element_located((By.XPATH, '//li[@class="el-menu-item submenu-title-noDropdown" and span[text()="下载中心"]]'))
                        )
        download_side.click()
        self.random_sleep(100)
        refresh_button = WebDriverWait(self.driver, 10).until(
                            EC.presence_of_element_located((By.XPATH, '//button[@class="el-button el-button--default el-button--small" and span[text()="刷新"]]'))
                        )
        refresh_button.click()
        self.random_sleep(10)

        download_button = WebDriverWait(self.driver, 30).until(
                            EC.presence_of_element_located((By.XPATH, '//button/span[text()="下载"]/..'))
                        )
        self.random_sleep(1)

        self.driver.execute_script("arguments[0].scrollIntoView(true);", download_button)
        self.driver.execute_script("return document.readyState") == "complete"
        self.random_sleep(1) 
        self.driver.execute_script("arguments[0].click();", download_button)

        delete_button = WebDriverWait(self.driver, 30).until(
                            EC.presence_of_element_located((By.XPATH, '//button/span[text()="删除 "]/..'))
                        )

        self.driver.execute_script("arguments[0].scrollIntoView(true);", delete_button)
        self.driver.execute_script("return document.readyState") == "complete"
        self.random_sleep(1)

        self.driver.execute_script("arguments[0].click();", delete_button)
        self.random_sleep(2)

        confirm_delete_button = WebDriverWait(self.driver, 30).until(
                                    EC.presence_of_element_located((By.CLASS_NAME, 'el-button.el-button--primary.el-button--mini'))
                                )
        self.driver.execute_script("arguments[0].scrollIntoView(true);", confirm_delete_button)
        self.driver.execute_script("arguments[0].click();", confirm_delete_button)

        downloaded_file = self.get_latest_downloaded_file()

        new_file_name = f"{self.site_name}_exported_click_button.xlsx"
        destination_path = os.path.join(self.task_download_dir, new_file_name)

        process_downloaded_file(downloaded_file, destination_path)
        logger.info(f"Processed and saved file to: {destination_path}")

        self.random_sleep(8)
        self.delete_downloaded_files()

    def page_html_to_excel(self):
        self.driver.switch_to.default_content()
        data_frame = pd.read_html(self.driver.page_source)[0]
        target_path = os.path.join(
            self.task_download_dir, f"{self.site_name}_page_html_to_excel.xlsx"
        )
        data_frame.to_excel(target_path, index=False)


    def download_file(self):
        #self.page_html_to_excel()  # One way to download the Excel file
        self.export_excel()        # Another way to download the Excel file; use either method

    def delete_downloaded_files(self):
        """Delete the original downloaded file after processing."""
        try:
            downloaded_file = self.get_latest_downloaded_file()
            if os.path.exists(downloaded_file):
                os.remove(downloaded_file)
                logger.info(f"Deleted original downloaded file: {downloaded_file}")
        except Exception as e:
            logger.error(f"Error deleting downloaded file: {e}")